package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    //保存小视频到mongoDB
    @Override
    public void saveVideo(Video video) {
        //执行保存
        mongoTemplate.save(video);
    }

    //查看视频列表
    @Override
    public List<Video> queryVideo(Long uid, Integer page, Integer pagesize) {
        //先从推荐系统中吧推荐的数据获取 在从mongoDB里获取
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + uid;
        String data = redisTemplate.opsForValue().get(redisKey);
        List<Video> videoList = null;
        //定义一个存放id的集合
        List<Long> vids = null;
        //定义推荐数 默认值0
        int recommendCount = 0;
        //有推荐数据
        if (StrUtil.isNotEmpty(data)) {
            String[] vidArr = StrUtil.split(data, ",");
            List<String> vidList = new ArrayList<>();
            Collections.addAll(vidList, vidArr);
            //计算分页
            //[0, 10]  page=1 pagesize=10
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pagesize);
            int startIndex = startEnd[0]; //开始 0 10 20
            int endIndex = Math.min(startEnd[1], vidList.size()); //结束 10 20 20
            vids = new ArrayList<>();
            for (int i = startIndex; i < endIndex; i++) {
                vids.add(Convert.toLong(vidList.get(i)));
            }
            //根据vid
            Query query = Query.query(Criteria.where("vid").in(vids)).with(Sort.by(Sort.Order.desc("created")));
            videoList = mongoTemplate.find(query, Video.class);
            recommendCount = vidList.size();
        }
        if (CollUtil.isEmpty(vids)) {
            //计算前面的推荐视频页数
            int totalPage = PageUtil.totalPage(recommendCount, pagesize);//2
            //直接从mongodb中获取
            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pagesize, Sort.by(Sort.Order.desc("created")));
            Query query = new Query();
            query.with(pageRequest);
            videoList = mongoTemplate.find(query, Video.class);
        }
        return videoList;
    }

    //根据id查询 Video对象
    public Video queryVideoById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Video.class);
    }

    //关注用户
    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }

        try {
            //需要将用户的关注列表，保存到redis中，方便后续的查询
            //使用redis的hash结构
            if (this.isFollowUser(userId, followUserId)) {
                return false;
            }

            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());

            this.mongoTemplate.save(followUser);

            //保存数据到redis
            String redisKey = this.getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    //取消关注用户
    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }

        if (!this.isFollowUser(userId, followUserId)) {
            return false;
        }

        //取消关注，删除关注数据即可
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId)
        );
        DeleteResult result = this.mongoTemplate.remove(query, FollowUser.class);
        if (result.getDeletedCount() > 0) {
            //同时删除redis中的数据
            String redisKey = this.getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().delete(redisKey, hashKey);

            return true;
        }

        return false;
    }

    //查询用户是否关注某个用户
    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = this.getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(followUserId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    //获取关注者的redisKey
    private String getVideoFollowUserKey(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }


}
